<template>

  <a-drawer :width="1200" :title="null" :closable="false" :visible="visible" destroy-on-close>
    <div class="box">

      <div class="header">
        <div class="header-item">
          <div class="left">当前区域</div>
          <div class="right">
            <span class="mr-5">{{ params.title }}</span>
            <span>附近{{ params.range }}</span>
            <span>KM以内公司</span>
          </div>
        </div>

        <div class="header-item">
          <div class="left">登记状态</div>
          <div class="right">
            <a-radio-group v-model:value="regIndex" v-for="(item,index) in regStatusList"
                           @change="changeRegStatus(index)">
              {{ regIndex }}
              <a-radio :value="index">{{ item }}</a-radio>
            </a-radio-group>

          </div>
        </div>
        <a-divider dashed style="margin: 10px"/>

        <div class="header-item justify-between">
          <div class="left">为你找到 <span class="text-blue">{{ companyList.length }}</span> 条相关结果
          </div>
          <div class="right">
            <a-space>
              <a-button type="link" @click="allSelect">{{ !isAll ? '全选' : '取消全选' }}</a-button>
              <a-button type="primary" ghost @click="addRules"
                        :disabled="selectCompanyList.length==0">添加线索
              </a-button>
              <a-button type="primary" ghost @click="exportPhotos"
                        :disabled="selectCompanyList.length==0">导出画像
              </a-button>
            </a-space>
          </div>
        </div>

      </div>
      <div class="search-list  mt-10" v-if="companyList.length" ref="listRef"
           @scroll="handleScroll">
        <div v-for="(item,index) in companyList" class="company-item" @click="showItem(item)">
          <div class="flex justify-between align-center">
            <div class=" " style="cursor: pointer" @click.stop="changeSelect(item)">
              <a-checkbox v-model:checked="item.checked"/>
              <span class="ml-5 name">{{ item.name }}</span>
            </div>
            <a-tag :color="statusColor[item.regStatus]?statusColor[item.regStatus]:''">
              {{ item.regStatus }}
            </a-tag>
          </div>
          <a-row :gutter="[0,12]" class="mt-20">
            <a-col span="4">
              <span>法定代表人：{{ item.legalPersonName }}</span>
            </a-col>
            <a-col span="4">
              <span>所在地区：{{ item.base }}</span>
            </a-col>
            <a-col span="4">
              <span>企业ID：{{ item.id }}</span>
            </a-col>
            <a-col span="4">
              <span>注册资本：{{ item.regCapital }}</span>
            </a-col>
            <a-col span="4">
              <span>成立日期：{{ item.estiblishTime.substring(0, 10) }}</span>
            </a-col>
            <a-col span="4">
              <span>组织机构代码：{{ item.orgNumber || "--" }}</span>
            </a-col>
          </a-row>
        </div>

      </div>
      <div v-else style="margin-top: 180px">
        <a-empty></a-empty>
      </div>
    </div>
    <div class="close-info " @click.stop="closeDrawer" v-if="visible">
      <right-outlined class="text-blue"/>
    </div>

    <!--    企业详情-->
    <CompanyDetail :visible="showDetail" :item="detailItem" @closeDetail="showDetail=false"/>

    <!--    添加线索-->
    <AttractingAddRuleModal :list="selectCompanyList"
                            :filter-num="filterNum"
                            :visible="ruleAddVisible"
                            @cancel="ruleAddVisible=false"
                            @success="addRuleSuccess"/>
  </a-drawer>

</template>

<script>
import {watch, toRefs, reactive, ref} from 'vue'
import {RightOutlined} from "@ant-design/icons-vue"
import CompanyDetail from '@/views/village/BusinessManage/modules/CompanyDetailDrawer.vue'
import Disabled from '@/views/village/HouseholdManagement/components/disabled.vue'
import AttractingAddRuleModal from "./AttractingAddRuleModal.vue"
import utils from '@/common/utils/utils'
import {xlsx} from '@/common/utils/xlsx'
import {message} from 'ant-design-vue'
import request from '@/common/utils/request'
import dayjs from 'dayjs'
import _ from 'lodash'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => ([])
    },
    params: {
      type: Object,
      default: () => ({})
    },
    reqParams: {
      type: Object,
      default: () => ({})
    },
  },
  components: {
    Disabled,
    CompanyDetail,
    RightOutlined,
    AttractingAddRuleModal
  },
  setup(props, context) {

    const state = reactive({
      showDetail: false,
      selectIndex: 0,
      detailId: 0,
      ruleAddVisible: false,
      mParams: {},
      companyList: [],
      detailItem: {},
      selectCompanyList: [],
      regIndex: -1,
      regStatusList: ["存续", "在业", "吊销", "注销", "停业", "撤销", "迁入", "迁出"],
      page: 1,
      listRef: null,
      filterNum: 0,
      statusColor: {
        "正常": "green",
        "存续": "green",
        "在业": "green",
        "吊销": "red",
        "注销": "red",
        "停业": "red",
        "清算": "orange",
        "撤销": "orange",
        "迁出": "blue",
        "迁入": "cyan",
      },
      isAll: false,
    })


    const requestMapCompanyList = () => {
      const params = {
        ...state.mParams
      }
      if (state.regIndex != -1) {
        params.regStatus = state.regStatusList[state.regIndex]
      }
      request.post("/org", "/business/clue/getCustomerByData", params).then(res => {
        console.log(res)
        if (state.page == 1) {
          state.companyList = res.list.map(item => {
            return {
              ...item,
              checked: false
            }
          });
        } else {
          state.companyList = state.companyList.concat(res.list.map(item => {
            return {
              ...item,
              checked: false
            }
          }))
        }
      })

    }

    const handleScroll = () => {
      if (state.listRef.scrollTop + state.listRef.clientHeight === state.listRef.scrollHeight) {
        state.page++;
        requestMapCompanyList()
      }
    }

    const init = () => {
      state.mParams = _.cloneDeep(props.reqParams)
      requestMapCompanyList()

    }

    const allSelect = () => {
      state.isAll = !state.isAll
      state.companyList.forEach(item => {
        item.checked = state.isAll
      })
      state.selectCompanyList = state.companyList.filter(item => {
        return item.checked == true
      })
    }

    const addRuleSuccess = () => {
      state.ruleAddVisible = false
    }
    const addRules = () => {
      fullData().then(res => {
        state.selectCompanyList = res
        state.ruleAddVisible = true;
      })
    }


    // 补全数据
    const fullData = () => {

      const ids = []
      state.companyList.forEach(item => {
        if (item.checked) {
          ids.push({
            id: item.id, base: item.base, companyType: getCompanyTypeName(item.company_type)
          })
        }
      })
      return new Promise((resolve) => {
        request.post("/org", "/business/clue/getClueByFullData", {ids: ids}).then(res => {
          state.filterNum = res.filterNum;
          resolve(res.list)
        })
      })

    }

    const columns = ref([
      {
        title: "公司名称",
        key: "name"
      },
      {
        title: "企业状态",
        key: "regStatus"
      },

      {
        title: "核准时间",
        key: "approvedTime"
      },
      {
        title: "法人",
        key: "legalPersonName"
      },
      {
        title: "所在地区",
        key: "base"
      },
      {
        title: "企业ID",
        key: "id"
      },
      {
        title: "联系方式",
        key: "contactInformation"
      },
      {
        title: "统一社会信用代码",
        key: "creditCode"
      },
      {
        title: "机构类型",
        key: "companyType"
      },
      {
        title: "组织机构代码",
        key: "orgNumber"
      },
      {
        title: "成立日期",
        key: "estiblishTime"
      },
      {
        title: "注册号",
        key: "regNumber"
      },
      {
        title: "注册资本",
        key: "regCapital"
      },
      {
        title: "经营开始时间",
        key: "fromTime"
      },
      {
        title: "经营结束时间",
        key: "toTime"
      },
      {
        title: "匹配方式",
        key: "matchType"
      }
    ])
    const formatTime = (time) => {
      return dayjs(time).format('YYYY-MM-DD')
    }

    const exportPhotos = () => {
      let listHanders = {};
      listHanders = columns.value.reduce((obj, v) => {
        obj[v.key] = v.title;
        return obj;
      }, {});
      state.isExport = true;
      fullData().then((res) => {
        if (state.filterNum != 0) {
          message.warning(`为您过滤${state.filterNum}条信息，过滤原因：暂未查询到联系方式`)
        }
        const tempList = res.map(item => {

          let company_type = getCompanyTypeName(item.company_type)
          return {
            ...item,
            companyType: company_type,
            toTime: item?.toTime ? item.toTime : "--",

          }
        })
        let list = utils.deepClone(tempList);
        xlsx(list, listHanders, "大数据获客");
        message.success("导出成功,请等待文件生成");
        state.isExport = false;
      });
    }

    const changeSelect = (item) => {
      item.checked = !item.checked
      state.selectCompanyList = state.companyList.filter(item => {
        return item.checked == true
      })

      console.log(state.companyList)
      state.isAll = state.selectCompanyList.length == state.companyList.length
    }


    const getCompanyTypeName = (value) => {
      let company_type = "公司";
      if (value == 2) {
        company_type = "香港公司会"
      } else if (value == 3) {
        company_type = "社会组织"
      } else if (value == 4) {
        company_type = "律所"
      } else if (value == 5) {
        company_type = "事业单位"
      } else if (value == 6) {
        company_type = "基金会"
      }
      return company_type
    }

    const showItem = (record) => {

      let company_type = getCompanyTypeName(record.companyType)
      state.detailItem = {
        id: record.id, "base": record.base, company_type: company_type
      }
      state.showDetail = true
    }
    const closeDrawer = () => {
      context.emit("toClose")
    }

    const changeRegStatus = (index) => {
      state.regIndex = index
      state.page = 1
      requestMapCompanyList()
    }

    watch(() => props.visible, (value) => {
      if (value) {
        init()
      } else {
        state.companyList = []
        state.selectCompanyList = []
      }
    })
    return {
      ...toRefs(state),
      closeDrawer,
      showItem,
      exportPhotos,
      addRules,
      allSelect,
      addRuleSuccess,
      changeSelect,
      changeRegStatus,
      handleScroll,


    }
  }
}
</script>

<style lang="less" scoped>

.close-info {
  position: fixed;
  z-index: 9999;
  top: calc(50% - 50px);
  right: 1200px;
  width: 30px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  background-color: white;
  font-size: 20px;
  cursor: pointer;

}

.box {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    height: 150px;

    .header-item {
      display: flex;
      align-items: center;
      height: 45px;

      .left {

      }

      .right {
        margin-left: 10px;
      }
    }

  }

  .search-list {
    overflow: scroll;
    flex: 1;
    padding: 0 10px 0 0;

    .company-item {
      border-bottom: 1px dashed #cccccc;
      border-radius: 5px;
      margin-top: 15px;
      padding: 20px;

      .name {
        font-weight: 600;
        font-size: 17px;
      }

    }

    .info-item {
      display: flex;
      align-items: center;
      margin-top: 10px;
      color: #666666;

      .title {
        width: 90px;
      }

      .content {
        flex: 1;
      }
    }

    .active-item {
      border: 1px solid #2681f3;
    }
  }

}
</style>